let querystring = require('querystring')
let URL = require('url');
module.exports=function page(req,count,pageSize,btnNum,page='page'){
    let {query,url}=req;
    query[page]=Number(query[page])
    if(query[page]<1||!query.hasOwnProperty(page)||isNaN(query[page])){
        query[page]=1;
    }
    if(count==0){
        data={
            limit:'',
            html:''
        }
        return data;
    }
    var urlPath=URL.parse(url).pathname;
    var accessUrl='';
    var tempQuery={...query};
    if(JSON.stringify(tempQuery)!='{}'){	//判断是否带有参数
        delete tempQuery[page];
        if(JSON.stringify(tempQuery)=='{}'){	//判断是否带有多个参数
            accessUrl=`${urlPath}?${page}=`;
        }else{
            otherQuery=querystring.stringify(tempQuery);
            accessUrl=`${urlPath}?${otherQuery}&${page}=`;
        }
    }else{
        accessUrl=`${urlPath}?${page}=`;
    }
    //动态limit查询
    var skip=(query[page]-1)*pageSize;
    var limit={skip:skip,limit:pageSize};
    var html=[];
    var pageNumAll=Math.ceil(count/pageSize);//向上取整 获取总的页面数
    if(btnNum>pageNumAll){
        btnNum=pageNumAll;
    }
    var numLeft=Math.floor((btnNum-1)/2);//向下取整 获取当前位置(设置在中间位置)的左边按钮个数
    var start=query[page]-numLeft;
    if(start<1){
        start=1;
    }else if(start>(pageNumAll-btnNum+1)){
        start=pageNumAll-btnNum+1;
    }
    var index=start;
    for(let i=0;i<btnNum;i++){
        if(start==query[page]){
            html[start-index]=`<span>${start}</span>`;
        }else{
            html[start-index]=`<a href="${accessUrl}${start}">${start}</a>`;
        }
        start++;
    }
    if(html.length>3){ //当按钮数大于3个时才加省略
        if(html.indexOf(`<a href="${accessUrl}1">1</a>`)==-1 && html.indexOf(`<span>1</span>`)==-1){
            //向数组前面删除
            html.shift();
            //向数组前面添加
            html.unshift(`<a href="${accessUrl}1">1</a> <span>...</span>`);
        }else if(html.indexOf(`<a href="${accessUrl}${pageNumAll}">${pageNumAll}</a>`)==-1 && html.indexOf(`<span>${pageNumAll}</span>`)==-1){
            //向数组后面删除
            html.pop();
            //向数组后面添加
            html.push(`<span>...</span> <a href="${accessUrl}${pageNumAll}">${pageNumAll}</a>`);
        }
    }
    {	//设置上一页和下一页
        if(query[page]!=1){
            var prev=query[page]-1;
            html.unshift(`<a href="${accessUrl}${prev}">上一页</a>`);//数组前加上一页
        }
        if(query[page]!=pageNumAll){
            var next=query[page]+1;
            html.push(`<a href="${accessUrl}${next}">下一页</a>`);//数组后加下一页
        }
    }
    html=html.join(' ');
    data={
        limit:limit,
        html:html
    }
    return data;
}
